import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from '@/api/axios'

// 认证相关的store
const AUTH_TOKEN_KEY = 'medical_guide_auth_token'
const USER_INFO_KEY = 'medical_guide_user_info'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref(localStorage.getItem(AUTH_TOKEN_KEY) || null)
  const userInfo = ref(JSON.parse(localStorage.getItem(USER_INFO_KEY)) || null)
  const isLoading = ref(false)
  const error = ref('')
  
  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  
  // 登录
  const login = async (phone, password, remember = false) => {
    try {
      isLoading.value = true
      error.value = ''
      
      // 模拟API请求
      // const response = await axios.post('/api/auth/login', { phone, password })
      // 模拟成功响应
      const response = {
        data: {
          token: 'mock-auth-token-' + Date.now(),
          userInfo: {
            id: 1,
            name: '用户' + Math.floor(Math.random() * 1000),
            phone: phone,
            avatar: null,
            role: 'patient',
            createdAt: new Date().toISOString()
          }
        }
      }
      
      // 保存认证信息
      token.value = response.data.token
      userInfo.value = response.data.userInfo
      
      // 持久化存储
      localStorage.setItem(AUTH_TOKEN_KEY, response.data.token)
      localStorage.setItem(USER_INFO_KEY, JSON.stringify(response.data.userInfo))
      
      // 如果选择"记住我"，可以设置更长的过期时间或使用cookie
      if (remember) {
        // 这里可以添加记住我相关的逻辑
      }
      
      return true
    } catch (err) {
      error.value = err.message || '登录失败，请检查账号密码'
      throw err
    } finally {
      isLoading.value = false
    }
  }
  
  // 注册
  const register = async (phone, password, code) => {
    try {
      isLoading.value = true
      error.value = ''
      
      // 模拟API请求
      // const response = await axios.post('/api/auth/register', { phone, password, code })
      // 模拟成功响应
      const response = {
        data: {
          token: 'mock-auth-token-' + Date.now(),
          userInfo: {
            id: Math.floor(Math.random() * 10000),
            name: '用户' + Math.floor(Math.random() * 1000),
            phone: phone,
            avatar: null,
            role: 'patient',
            createdAt: new Date().toISOString()
          }
        }
      }
      
      // 保存认证信息
      token.value = response.data.token
      userInfo.value = response.data.userInfo
      
      // 持久化存储
      localStorage.setItem(AUTH_TOKEN_KEY, response.data.token)
      localStorage.setItem(USER_INFO_KEY, JSON.stringify(response.data.userInfo))
      
      return true
    } catch (err) {
      error.value = err.message || '注册失败，请重试'
      throw err
    } finally {
      isLoading.value = false
    }
  }
  
  // 登出
  const logout = () => {
    token.value = null
    userInfo.value = null
    
    // 清除本地存储
    localStorage.removeItem(AUTH_TOKEN_KEY)
    localStorage.removeItem(USER_INFO_KEY)
  }
  
  // 刷新用户信息
  const refreshUserInfo = async () => {
    if (!token.value) return
    
    try {
      // 模拟API请求
      // const response = await axios.get('/api/auth/user-info')
      // 模拟成功响应
      const response = {
        data: {
          id: userInfo.value?.id || 1,
          name: userInfo.value?.name || '用户' + Math.floor(Math.random() * 1000),
          phone: userInfo.value?.phone || '',
          avatar: null,
          role: 'patient',
          updatedAt: new Date().toISOString()
        }
      }
      
      userInfo.value = response.data
      localStorage.setItem(USER_INFO_KEY, JSON.stringify(response.data))
    } catch (err) {
      // 刷新失败可以选择登出用户
      logout()
      throw err
    }
  }
  
  // 获取验证码
  const getVerificationCode = async (phone) => {
    try {
      isLoading.value = true
      error.value = ''
      
      // 模拟API请求
      // const response = await axios.post('/api/auth/send-code', { phone })
      
      // 模拟发送成功
      return true
    } catch (err) {
      error.value = err.message || '发送验证码失败，请重试'
      throw err
    } finally {
      isLoading.value = false
    }
  }
  
  // 重置密码
  const resetPassword = async (phone, code, newPassword) => {
    try {
      isLoading.value = true
      error.value = ''
      
      // 模拟API请求
      // const response = await axios.post('/api/auth/reset-password', { phone, code, newPassword })
      
      // 模拟成功
      return true
    } catch (err) {
      error.value = err.message || '重置密码失败，请重试'
      throw err
    } finally {
      isLoading.value = false
    }
  }
  
  return {
    // 状态
    token,
    userInfo,
    isLoading,
    error,
    
    // 计算属性
    isLoggedIn,
    
    // 方法
    login,
    register,
    logout,
    refreshUserInfo,
    getVerificationCode,
    resetPassword
  }
})